import re

from pymongo import MongoClient, ReplaceOne, UpdateOne

# 有密码的Mongo
# client = MongoClient('mongodb://admin:admin@localhost:27017/')

# 没密码的Mongo
client = MongoClient('mongodb://localhost:27018/')

# 使用Mongo里的某个DB（Document）
db = client.mydb


# 显示所有已经存在的DB
# for db in client.list_databases():
#     print(db)
# list(client.list_databases())
# print(db)


# 插入一条数据
def add_one_user():
    db.User.insert_one({
        'name': 'Toby',
        'age': 18
    })


# 插入多条数据
def add_many_users():
    db.User.insert_many([{
        'name': 'Tom',
        'age': 10
    }, {
        'name': 'Toby',
        'age': 'unknown',
        'hobbies': ['write bugs', 'raise dogs']
    }])


# 查询多个数据
def show_users():
    # 一个表里所有数据
    for e in db.User.find():
        print(e)

    # 匹配条件的多条数据
    for e in db.User.find({'name': 'Toby'}):
        print(e)


# 查询单个数据
def query_user(name):
    return db.User.find_one({'name': name})


# 忽略大小写
def query_user_ignore_case(name):
    return db.User.find_one({'name': re.compile(name, re.IGNORECASE)})


# 使用运算符 https://docs.mongodb.com/manual/reference/operator/query/
def query_teenager():
    return db.User.find_one({'age': {'$lt': 18}})


# 修改一个数据
def update_user(user, attributes: dict):
    user.update(attributes)
    result = db.User.replace_one({'_id': user['_id']}, user, upsert=True)
    return {'affected_count': result.modified_count}


# u = query_user_ignore_case('toby')
# result = update_user(u, {'code': 'python'})

# 修改多个数据，注意有坑
def update_many():
    todo = [
        UpdateOne({'age': 19}, {'$set': {'name': 'Toby'}}),
        ReplaceOne({'name': 'Tom'}, {'age': 19}),  # name 会被吃掉
    ]
    result = db.User.bulk_write(todo)
    print(result.matched_count)


# update_many()


def delete_user(name):
    result = db.User.delete_one({'name': name})
    return {'affected_count': result.deleted_count}


if __name__ == '__main__':
    # add_many_users()
    # add_one_user()
    # u = query_user_ignore_case('toby')
    # result = update_user(u, {'code': 'python'})
    # # result = delete_user(name='Toby')
    # print(result)
    #
    # print(query_teenager())
    update_many()
    show_users()
